import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import { asyncRoutes } from '@/router/modules/AsyncRoute'
import { constantRoutes } from '@/router'
import router from '@/router'
import { hasPermission } from '@/utils/hasPermission'
import {hasRole} from "@/utils/hasRole";
import type {UserVO} from "@/types/vo/UserVO";

// 过滤路由，两种方式，一种是设置noAuth为true，一种是该路由不添加到路由表中,既要有权限又要有角色， 不过在路由表可以只设置一个也可以两个都设置或者都不设置， 一般情况下，只设置一个就可以了，设置角色就可以了，因为角色是权限的集合
const filterRoutes = (
  routes: RouteRecordRaw[],
  permissions: string[],
  roles: string[],
): RouteRecordRaw[] => {
  const result: RouteRecordRaw[] = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(permissions, tmp) && hasRole(roles, tmp)) {
      // 递归过滤子路由
      if (tmp.children) {
        tmp.children = filterRoutes(tmp.children, permissions, roles)
      }
      result.push(tmp)
    }
  })
  return result
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 用户token
    const token = ref('')
    const setToken = (newToken: string) => {
      token.value = newToken
    }
    const clearToken = () => {
      setToken('')
    }
    // 用户信息
    const userInfo = ref<UserVO>()

    const setUserInfo = (newUserInfo: UserVO) => {
      userInfo.value = newUserInfo
      //在设置用户信息时，生成用户拥有的权限路由
      generateAuthRoutes()
    }

    const clearUserInfo = () => {
      setUserInfo({} as UserVO)
    }

    // 用户拥有的权限路由
    const authRoutes = ref<RouteRecordRaw[]>([])
    // 设置用户拥有的权限路由
    const setAuthRoutes = (routes: RouteRecordRaw[]) => {
      authRoutes.value = routes
    }
    const clearAuthRoutes = () => {
      setAuthRoutes([])
    }

    // 用户拥有的全部路由
    const allRoutes = ref<RouteRecordRaw[]>([])
    const setAllRoutes = (routes: RouteRecordRaw[]) => {
      allRoutes.value = routes
    }
    const clearAllRoutes = () => {
      setAllRoutes([])
    }

    // 生成用户拥有的权限路由
    const generateAuthRoutes = () => {
      const permissions = userInfo.value?.permissions || []
      const roles = userInfo.value?.roles || []
      const routes = filterRoutes(asyncRoutes, permissions, roles)
      setAuthRoutes(routes)
      setAllRoutes(constantRoutes.concat(routes))
      // 动态添加路由
      authRoutes.value.forEach(route => {
        router.addRoute(route)
      })
    }

    const logout = async () => {
      await router.push('/login')
      clearToken()
      clearUserInfo()
      clearAuthRoutes()
      clearAllRoutes()
    }

    return {
      token,
      setToken,
      clearToken,
      userInfo,
      setUserInfo,
      clearUserInfo,
      logout,
      authRoutes,
      setAuthRoutes,
      allRoutes,
      setAllRoutes,
      generateAuthRoutes,
    }
  },
  {
    persist: {
      pick:['token', 'userInfo']
    }
  },
)
